<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <row>
      <Col :span="7">
        <div style="padding: 16px 0 0 16px">
          <Card style="height: 100vh">
            <BasicForm @register="chatregisterForm"> </BasicForm>
            <div style="margin-left: 30px">
              <span v-if="checkNum.length == 0">您暂未选择视频</span>
              <span v-else>您勾选了{{ checkNum.length }}条视频</span>
            </div>
            <div style="text-align: center">
              <a-button type="primary" @click="handleOK">生成私信任务</a-button>
            </div>
          </Card>
        </div>
      </Col>
      <Col :span="17">
        <div style="padding: 16px 16px 0 16px" class="cardpadding">
          <Card>
            <BasicTable @register="registerTableModel">
              <template #toolbar>
                <div style="display: flex; align-items: center; justify-content: space-around">
                  勾选前
                  <div style="width: 20%">
                    <Input style="display: inline" v-model:value="dataIdList"></Input>
                  </div>

                  条视频
                  <a-button type="primary" @click="check">确认勾选</a-button>
                  <a-button @click="Clear">取消勾选</a-button>
                </div>
                <!-- <a-button type="primary" @click="handleCreate">新增任务</a-button> -->
              </template>
            </BasicTable>
          </Card>
        </div>
      </Col>
    </row>

    <AccountModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { useModal } from '@/components/Modal';
  import { BasicTable, useTable } from '@/components/Table';
  import { PageWrapper } from '@/components/Page';
  import { columnsModels, searchFormSchema, chatAccountFormSchema } from './account.data';
  import AccountModal from './AccountModal.vue';
  import { getCommentMarchPageAPI, getCommentMarchPageAPICheck } from '@/api/demo/videoList';
  import { getdeviceToOwnerAPI } from '@/api/demo/videoList';
  import { createTaskChat } from '@/api/demo/chat';
  import {
    Tooltip,
    Select,
    SelectOption,
    RadioGroup,
    Radio,
    message,
    Card,
    Row,
    ColProps,
    Col,
    Input,
  } from 'ant-design-vue';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  defineOptions({ name: 'AccountManagement' });
  const dataIdList = ref('');
  interface TableRow {
    id: String;
    userNo: string;
    url?: string;
    dataId?: string;
  }
  const TabelData = ref<TableRow[]>([]);
  const deviceList = ref<any[]>([]);
  const total = ref(0);
  const checkNum = ref<any[]>([]);
  const searchInfo = reactive<Recordable>({});
  const [registerModal, { openModal }] = useModal();
  // 方法定义
  const [chatregisterForm, { getFieldsValue }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: chatAccountFormSchema,
    showActionButtonGroup: false,
  });
  const [
    registerTableModel,
    {
      reload,
      updateTableDataRecord,
      getSelectRows,
      getForm,
      setSelectedRowKeys,
      clearSelectedRowKeys,
    },
  ] = useTable({
    api: getCommentMarchPageAPI,
    rowKey: 'id',
    columns: columnsModels,
    showTableSetting: true,
    bordered: true,
    handleSearchInfoFn(info) {
      return info;
    },
    useSearchForm: true,
    formConfig: {
      schemas: searchFormSchema,
      labelWidth: 120,
      autoSubmitOnEnter: true,
    },
    rowSelection: {
      type: 'checkbox',
      onChange: (selectedRowKeys, selectedRows) => {
        checkNum.value = selectedRowKeys;
      },
    },
  });
  function handleSuccess({ isUpdate, values }) {
    if (isUpdate) {
      updateTableDataRecord(values.id, values);
    } else {
      reload();
    }
  }
  // function handleCreate() {
  //   const selectedRows = getSelectRows();
  //   let userNoList = [];
  //   selectedRows.forEach((row) => {
  //     if (!row.userNo) {
  //       const matchedRow = TabelData.value.find((item) => item.id === row.id);
  //       if (matchedRow && matchedRow.userNo) {
  //         userNoList.push(matchedRow.userNo);
  //       }
  //     } else {
  //       userNoList.push(row.userNo);
  //     }
  //   });
  //   openModal(true, {
  //     userNoList: userNoList,
  //     isUpdate: false,
  //   });
  // }

  async function check() {
    const form = getForm();
    const searchFormValues = await form.getFieldsValue();
    const data = await getCommentMarchPageAPICheck({
      ...searchFormValues,
      current: 1,
      size: dataIdList.value,
    });
    TabelData.value = data.items;
    const dataIdArray: string[] = [];
    if (Array.isArray(data.items)) {
      // 遍历 data.item 并将 dataId 添加到数组中
      data.items.forEach((item) => {
        if (item.id) {
          dataIdArray.push(item.id);
        }
      });
    }
    setSelectedRowKeys(dataIdArray);
  }

  async function Clear() {
    clearSelectedRowKeys();
  }

  async function handleOK() {
    const selectedRows = getSelectRows() as TableRow[];
    let userNos: string[] = [];
    if (selectedRows.length == 0) {
      message.error('请先选择人员')
      return 
    }
    selectedRows.forEach((row) => {
      if (!row.userNo) {
        const matchedRow = TabelData.value.find((item) => item.id === row.id);
        if (matchedRow && matchedRow.userNo) {
          userNos.push(matchedRow.userNo);
        }
      } else {
        userNos.push(row.userNo);
      }
    });

    const deviceLabels = getFieldsValue()
      .devices.map((deviceId) => {
        const device = deviceList.value.find((d) => d.value === deviceId);
        return device ? device.label : '';
      })
      .filter((label) => label !== ''); // 过滤掉空字符串
    const devicesString = deviceLabels.join(', '); // 将设备标签用逗号拼接起来

    const Data = {
      ...getFieldsValue(),
      userNos: userNos,
      devices: devicesString,
    };

    const data = await createTaskChat(Data);

    message.success(t('sys.configuration.succesSubmit'));
  }

  onMounted(async () => {
    try {
      // 获取设备管理
      const deviceresponse = await getdeviceToOwnerAPI();
      deviceList.value = deviceresponse.data; // 假设接口返回的数据结构为 { data: [] }
    } catch (error) {
      console.error('获取模板列表失败', error);
    }
  });
</script>

<style scoped>
  .cardpadding :deep(:where(.css-dev-only-do-not-override-n9spb6).ant-card .ant-card-body) {
    padding: 0 !important;
  }
</style>
